﻿using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using HsServerHa.Core;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.Entity.Models.SqlserverMirror;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.FileHelper;
using HsServerHa.Utility.SQLite;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection.Metadata;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace HsServerHa.Utility.NetWork
{
    public class HttpServerService
    {
        private static bool isExcute = true;
        public static string NetworkCardName { get; set; }
        private static HttpListener listener = null;

        /// <summary>
        /// 网卡名称
        /// </summary>
        /// <param name="networkCardName"></param>
        public static void Start(string networkCardName)
        {
            if (listener != null)
            {
                return;
            }
            NetworkCardName = networkCardName;
            if (string.IsNullOrEmpty(networkCardName))
            {
                return;
            }
            System.Threading.ThreadPool.QueueUserWorkItem(w => Excute());//单独开启一个线程执行监听消息
        }

        private static async void Excute()
        {
            listener = new HttpListener();
            try
            {
                if (HttpListener.IsSupported)
                {
                    if (!listener.IsListening)
                    {
                        var dt = DbHelperSQLite.Query("select  * from VirtuallyManage")?.Tables?[0];
                        var list = DataHelpers.ConvertToModel<VirtuallyManageEntity>(dt);
                        var msFirst = list.FirstOrDefault();
                        if (msFirst == null)
                        {
                            return;
                        }
                        listener.Prefixes.Add($"http://{msFirst.CurrIP.ToString()}:{ConfigurationManager.AppSettings["HttpPort"].ToString()}/");
                        //var listNet = NetWorkHelper.GetNetworkInfo();
                        //foreach (var net in listNet)
                        //{
                        //    IPInterfaceProperties Netip = net.GetIPProperties();
                        //    UnicastIPAddressInformationCollection ipCollection = Netip.UnicastAddresses;
                        //    if (net.Name == NetworkCardName)
                        //    {
                        //        foreach (UnicastIPAddressInformation item in ipCollection)
                        //        {
                        //            if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        //            {
                        //                listener.Prefixes.Add($"http://{item.Address.ToString()}:{ConfigurationManager.AppSettings["HttpPort"].ToString()}/");

                        //                LoggerHelper.Info($"http://{item.Address.ToString()}:{ConfigurationManager.AppSettings["HttpPort"].ToString()}/");
                        //                Thread.Sleep(1000);
                        //                break;
                        //                //添加需要监听的url
                        //            }
                        //        }
                        //    }

                        //}

                        listener.Start(); //开始监听端口，接收客户端请求
                        LoggerHelper.Info("开启Http服务");
                    }
                    HttpListenerResponse response = null;
                    while (isExcute)
                    {
                        try
                        {
                            //阻塞主函数至接收到一个客户端请求为止  等待请求
                            HttpListenerContext context = listener.GetContext();
                            //解析请求
                            HttpListenerRequest request = context.Request;
                            //构造响应
                            response = context.Response;
                            //http请求方式：get，post等等
                            string httpMethod = request.HttpMethod?.ToLower();
                            string rawUrl = request.RawUrl;//不包括IP和端口
                            var Url = request.Url;//全路径

                            var responseString = string.Empty;
                            HttpResponseResultModel<object> httpResponseResultModel = new HttpResponseResultModel<object>() { IsSuccess = false };
                            if (httpMethod == "get")
                            {
                                //获取查询参数
                                var queryString = request.QueryString;
                                // 请求接口 test/method?id=5
                                //键值对方式 string val = queryString["key"];
                                //string val = queryString["id"];val的值是5
                                rawUrl = rawUrl.Split('?')[0];
                                switch (rawUrl)
                                {
                                    case "/getMasterInfo":
                                        //查询主机信息
                                        //var sqlMaster = "SELECT * FROM  MasterSlaveBind where 1=1";
                                        //sqlMaster += " and IsMaster='true'";//测试临时干掉
                                        //var dtMaster = DbHelperSQLite.Query(sqlMaster)?.Tables?[0];
                                        //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster);
                                        var masterList = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().Where(x => x.IsMaster == "true").ToListAsync().ConfigureAwait(false);

                                        httpResponseResultModel.IsSuccess = true;
                                        httpResponseResultModel.BackResult = masterList?.FirstOrDefault();
                                        responseWrite(httpResponseResultModel, response);
                                        break;
                                    case "/getMasterHeartInfo":
                                        //查询心跳信息
                                        //var sqlHeart = "SELECT * FROM  HeartManage where 1=1";
                                        //sqlHeart += " and IsLocal='true'";//测试临时干掉
                                        //var dtHeart = DbHelperSQLite.Query(sqlHeart)?.Tables?[0];
                                        //var HeartList = DataHelpers.ConvertToModel<HeartEntity>(dtHeart);
                                        var HeartList = await SQLiteHelper.TableAsync<HeartEntity>().Where(x => x.IsLocal == "true").ToListAsync().ConfigureAwait(false);

                                        httpResponseResultModel.IsSuccess = true;
                                        httpResponseResultModel.BackResult = HeartList;
                                        responseWrite(httpResponseResultModel, response);
                                        break;
                                    case "/getSlaveInfo":
                                        //var sqlMaster1 = "SELECT * FROM  MasterSlaveBind where 1=1";
                                        //var dtMaster1 = DbHelperSQLite.Query(sqlMaster1)?.Tables?[0];
                                        //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster1);
                                        var masterList1 = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().ToListAsync().ConfigureAwait(false);

                                        httpResponseResultModel.IsSuccess = true;
                                        httpResponseResultModel.BackResult = masterList1;
                                        responseWrite(httpResponseResultModel, response);
                                        break;
                                    case "/getFilesExits":
                                        string val = queryString["fileStr"];
                                        if (File.Exists($@"{val}"))
                                        {
                                            //存在 
                                            httpResponseResultModel.IsSuccess = true;
                                        }
                                        else
                                        {
                                            //不存在 
                                            httpResponseResultModel.IsSuccess = false;
                                        }
                                        responseWrite(httpResponseResultModel, response);
                                        break;
                                    case "/getOppositeServerIsMasterOrSlaveInfo":
                                        //var sqlMaster2 = "SELECT * FROM  MasterSlaveBind where 1=1";
                                        //var dtMaster2 = DbHelperSQLite.Query(sqlMaster2)?.Tables?[0];

                                        var masterList2 = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().ToListAsync().ConfigureAwait(false);
                                        if (masterList2.Count > 0)
                                        {
                                            var masterFirst = masterList2.FirstOrDefault();
                                            httpResponseResultModel.IsSuccess = Convert.ToBoolean(masterFirst?.IsMaster ?? "false");
                                            httpResponseResultModel.BackResult = masterList2?.FirstOrDefault();

                                        }
                                        else
                                        {
                                            httpResponseResultModel.IsSuccess = false;
                                        }
                                        responseWrite(httpResponseResultModel, response);
                                        break;
                                    case "/getRemoteCardInfo":
                                        try
                                        {
                                            List<NetWorkCardInfoEntity> list = new List<NetWorkCardInfoEntity>();
                                            var adapterList = NetWorkHelper.GetNetworkInfo();
                                            foreach (var adapter in adapterList)
                                            {
                                                string Name = adapter.Name;
                                                NetWorkCardInfoEntity item = new NetWorkCardInfoEntity();
                                                item.CardName = adapter.Name;
                                                var adapterItem = NetWorkHelper.GetAdapterByName(Name);
                                                IPInterfaceProperties ip = adapter.GetIPProperties();
                                                UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                                                foreach (UnicastIPAddressInformation UII in ipCollection)
                                                {
                                                    if (UII.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                                    {
                                                        item.IP = UII.Address.ToString();
                                                        break;
                                                    }
                                                }
                                                //获取远程Mac
                                                if (adapterItem != null)
                                                {
                                                    PhysicalAddress pa = adapter.GetPhysicalAddress();
                                                    byte[] bytes = pa.GetAddressBytes();
                                                    StringBuilder sb = new StringBuilder();
                                                    for (int i = 0; i < bytes.Length; i++)
                                                    {
                                                        sb.Append(bytes[i].ToString("X2"));
                                                        if (i != bytes.Length - 1)
                                                        {
                                                            sb.Append('-');
                                                        }
                                                    }
                                                    item.RemoteMac = sb.ToString();
                                                }
                                                list.Add(item);
                                            }
                                            httpResponseResultModel.IsSuccess = true;
                                            httpResponseResultModel.BackResult = list;
                                        }
                                        catch (Exception ex)
                                        {
                                            httpResponseResultModel.IsSuccess = false;
                                            httpResponseResultModel.ErrorMessage = ex.Message;
                                            LoggerHelper.Error(ex.Message + ex.ToString());
                                            LoggerHelper.Error(ex.StackTrace);
                                        }

                                        responseWrite(httpResponseResultModel, response);
                                        break;
                                    case "/getRemoteCardInfoByKey":
                                        {
                                            string key = queryString["ProgramKey"];
                                            //var dataSet = DbHelperSQLite.Query($"SELECT * FROM MultipleNetworkCardManage  where ProgramKey='{key}' ", null);
                                            //DataTable dt = dataSet.Tables[0];
                                            //var  list = DataHelpers.ConvertToModel<MultipleNetworkCardManageEntity>(dt);
                                            var list = await SQLiteHelper.TableAsync<MultipleNetworkCardManageEntity>().Where(x => x.ProgramKey == key).ToListAsync().ConfigureAwait(false);

                                            httpResponseResultModel.BackResult = list?.FirstOrDefault();
                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/getRemoteSystemInfo":
                                           
                                        {
                                            var systemInfo= SystemConfigHelper.GetSystemConfig();                                           
                                            httpResponseResultModel.BackResult = systemInfo;
                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }

                                    default:
                                        {
                                            LoggerHelper.Error(rawUrl + "接口不存在");
                                            httpResponseResultModel.IsSuccess = false;
                                            httpResponseResultModel.BackResult = "接口不存在";
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                }
                            }
                            else if (httpMethod == "post")
                            {
                                //请求接口 test/postMethod 格式是json
                                //{
                                //    "id":5,
                                //     "name":"zs"
                                //}
                                //获取pots请求的请求体，json格式的字符串
                                var reader = new StreamReader(request.InputStream);
                                var questBody = reader.ReadToEnd();
                                switch (rawUrl)
                                {
                                    case "/postSlaveInfo":
                                        {
                                            if (!string.IsNullOrEmpty(questBody))
                                            {
                                                MasterSlaveBindEntity model = JsonConvert.DeserializeObject<MasterSlaveBindEntity>(questBody);
                                                if (model != null)
                                                {
                                                    // To Do
                                                    httpResponseResultModel.IsSuccess = true;
                                                    var slaveInfoSql = $"update MasterSlaveBind SET SlaveIP='{model.SlaveIP}' WHERE 1=1 ";
                                                    //sqlMaster += " and IsMaster='true'";//测试临时干掉
                                                    var result = SQLiteHelper.ExecuteSql(slaveInfoSql);
                                                    if (result <= 0)
                                                    {
                                                        httpResponseResultModel.IsSuccess = false;
                                                        httpResponseResultModel.ErrorMessage = "修改失败";
                                                    }
                                                    responseWrite(httpResponseResultModel, response);
                                                }
                                            }
                                            break;
                                        }
                                    case "/postMasterRestart":
                                        {
                                            //var sql = "select  * from VirtuallyManage";
                                            //var dtMaster = DbHelperSQLite.Query(sql)?.Tables?[0];
                                            //var xnList = DataHelpers.ConvertToModel<VirtuallyManageEntity>(dtMaster);
                                            var xnList = await SQLiteHelper.TableAsync<VirtuallyManageEntity>().ToListAsync().ConfigureAwait(false);

                                            var xnFirst = xnList.FirstOrDefault();
                                            if (xnFirst != null)
                                            {
                                                //var cmd = $"/c" + $"& netsh interface set interface {xnFirst.NetworkCardName} admin=disable && netsh interface set interface {xnFirst.NetworkCardName} admin=enable";

                                                //NetWorkHelper.HandleCMDCommand(cmd);
                                                httpResponseResultModel.IsSuccess = true;
                                            }
                                            else
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/setBindHeartInfo":
                                        {
                                            HeartEntity model = JsonConvert.DeserializeObject<HeartEntity>(questBody);
                                            SQLiteHelper.ExecuteSql($"update HeartManage set MasterHeartIPBind='{model.HeartIP}'");
                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postSwitchSlave":
                                        {
                                            WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("Slave"), "SwitchMasterSlave");
                                            //主机切从机
                                            //List<MultipleNetworkCardManageEntity> list =await SQLiteHelper.TableAsync<MultipleNetworkCardManageEntity>().Where(x => x.IsEnable == "是").ToListAsync().ConfigureAwait(false);
                                            //var MultipleNetworkCard = list.FirstOrDefault();
                                            //Task.Run(() =>
                                            //{
                                            //    ReSetMacAddress(MultipleNetworkCard.NetworkCardName, GetRandMac());
                                            //});
                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postSwitchMaster":
                                        {
                                            WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("Master"), "SwitchMasterSlave");
                                            //从机切主机
                                            //List<MultipleNetworkCardManageEntity> list = await SQLiteHelper.TableAsync<MultipleNetworkCardManageEntity>().Where(x => x.IsEnable == "是").ToListAsync().ConfigureAwait(false);
                                            //var MultipleNetworkCard = list.FirstOrDefault();
                                            //Task.Run(() =>
                                            //{
                                            //    ReSetMacAddress(MultipleNetworkCard.NetworkCardName, MultipleNetworkCard.MAC);
                                            //});
                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postAddProgram":
                                        {
                                            ProgramManageEntity model = JsonConvert.DeserializeObject<ProgramManageEntity>(questBody);

                                            SQLiteHelper.ExecuteSql($"insert into ProgramManage (ProgramKey,ProgramName,Src,StartupSeq,Delayed,IsEnable,CreateTime)" +
                                                    $" values('{model.ProgramKey}','{model.ProgramName}','{model.Src}','{model.StartupSeq}','{model.Delayed}','{model.IsEnable}','{DateTime.Now.ToString()}')");

                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postDelProgram":
                                        {
                                            ProgramManageEntity model = JsonConvert.DeserializeObject<ProgramManageEntity>(questBody);

                                            SQLiteHelper.ExecuteSql($"delete from  ProgramManage where ProgramKey='{model.ProgramKey}' ");

                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postUpdateProgram":
                                        {
                                            ProgramManageEntity model = JsonConvert.DeserializeObject<ProgramManageEntity>(questBody);

                                            SQLiteHelper.ExecuteSql($"update ProgramManage set  ProgramName='{model.ProgramName}',Src='{model.Src}',StartupSeq='{model.StartupSeq}',Delayed='{model.Delayed}',IsEnable='{model.IsEnable}' where  ProgramKey='{model.ProgramKey}' ");

                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postAddSQLData":
                                        {
                                            try
                                            {
                                                SQLManageEntity model = JsonConvert.DeserializeObject<SQLManageEntity>(questBody);

                                                SQLiteHelper.ExecuteSql($"insert into SQLManage (ProgramKey,DBName,Port,UserId,UserPwd,IsEnable,CreateTime)" +
                                        $" values('{model.ProgramKey}','{model.DBName}','{model.Port}','{model.UserId}','{model.UserPwd}','{model.IsEnable}','{DateTime.Now.ToString()}')");

                                                httpResponseResultModel.IsSuccess = true;
                                            }
                                            catch (Exception ex)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                            }

                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postUpdateSQLData":
                                        {
                                            SQLManageEntity model = JsonConvert.DeserializeObject<SQLManageEntity>(questBody);

                                            SQLiteHelper.ExecuteSql($"update SQLManage set DBName='{model.DBName}',Port='{model.Port}',UserId='{model.UserId}',UserPwd='{model.UserPwd}',IsEnable='{model.IsEnable}'  where ProgramKey='{model.ProgramKey}'");

                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postDelSQLData":
                                        {
                                            SQLManageEntity model = JsonConvert.DeserializeObject<SQLManageEntity>(questBody);

                                            SQLiteHelper.ExecuteSql($"delete from  SQLManage where ProgramKey='{model.ProgramKey}' ");

                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postSwatchSQLData":
                                        {
                                            #region 数据库主切换成从
                                            //var sqlMaster = "SELECT * FROM  MasterSlaveBind where 1=1";
                                            //sqlMaster += " and IsMaster='true'";//测试临时干掉
                                            //var dtMaster = DbHelperSQLite.Query(sqlMaster)?.Tables?[0];
                                            //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster);
                                            var masterList = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().Where(x => x.IsMaster == "true").ToListAsync().ConfigureAwait(false);


                                            //var sql = "SELECT * FROM SQLManage where IsEnable='是'";
                                            //var Sqldt = DbHelperSQLite.Query(sql)?.Tables?[0];
                                            //List<SQLManageEntity> Sqllist = DataHelpers.ConvertToModel<SQLManageEntity>(Sqldt);
                                            var Sqllist = await SQLiteHelper.TableAsync<SQLManageEntity>().Where(x => x.IsEnable == "是").ToListAsync().ConfigureAwait(false);

                                            foreach (var item in Sqllist)
                                            {
                                                var DBConnectionStr = ConfigurationManager.AppSettings["DBConnectionString"].ToString();
                                                DBConnectionStr = DBConnectionStr.Replace("#IPAddress#", masterList[0].MasterIP + "," + item.Port);
                                                DBConnectionStr = DBConnectionStr.Replace("#DBName#", item.DBName);
                                                DBConnectionStr = DBConnectionStr.Replace("#UserId#", item.UserId);
                                                DBConnectionStr = DBConnectionStr.Replace("#UserPwd#", item.UserPwd);
                                                DbHelperSQL db = new DbHelperSQL(DBConnectionStr);
                                                db.ExecuteSql($"USE master;  ALTER DATABASE [{item.DBName}] SET PARTNER FAILOVER");
                                            }
                                            #endregion
                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/AddMulttipRemoteCardInfo":
                                        {
                                            try
                                            {
                                                MultipleNetworkCardManageEntity model = JsonConvert.DeserializeObject<MultipleNetworkCardManageEntity>(questBody);
                                                var sql = $"insert into MultipleNetworkCardManage" +
                                                    $" (ProgramKey,CurrIP,NetworkCardName,RemoteIP,SubnetMask,Gateway,DNS1,DNS2,MAC,CurrentMAC,RemoteMAC,IsSyncMAC," +
                                                    $"VirtuallyIP,ReferIP,IsMaster,IsEnable,CreateTime)" +
                                                    $" values('{model.ProgramKey}','{model.CurrIP}','{model.NetworkCardName}'," +
                                                    $"'{model.RemoteIP}','{model.SubnetMask}','{model.Gateway}','{model.DNS1}'" +
                                                    $",'{model.DNS2}','{model.MAC}','{model.RemoteMAC}','{model.CurrentMAC}',{model.IsSyncMAC},'{model.VirtuallyIP}','{model.ReferIP}'" +
                                                    $",'{model.IsMaster}','{model.IsEnable}','{DateTime.Now.ToString()}')";
                                                var i = SQLiteHelper.ExecuteSql(sql);
                                                if (i >= 0)
                                                {
                                                    httpResponseResultModel.IsSuccess = true;
                                                }
                                                else
                                                {
                                                    LoggerHelper.Error("添加失败：-》" + sql);
                                                    httpResponseResultModel.ErrorMessage = "添加失败：-》" + sql;
                                                    httpResponseResultModel.IsSuccess = false;
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/UpdateMulttipRemoteCardInfo":
                                        {
                                            try
                                            {
                                                MultipleNetworkCardManageEntity model = JsonConvert.DeserializeObject<MultipleNetworkCardManageEntity>(questBody);
                                                var i = SQLiteHelper.ExecuteSql($"update MultipleNetworkCardManage set CurrIP='{model.CurrIP}',NetworkCardName='{model.NetworkCardName}',RemoteIP='{model.RemoteIP}',SubnetMask='{model.SubnetMask}',Gateway='{model.Gateway}',DNS1='{model.DNS1}',DNS2='{model.DNS2}',MAC='{model.MAC}',CurrentMAC='{model.RemoteMAC}',RemoteMAC='{model.CurrentMAC}',IsSyncMAC={model.IsSyncMAC},VirtuallyIP='{model.VirtuallyIP}',ReferIP='{model.ReferIP}',IsMaster='{model.IsMaster}',IsEnable='{model.IsEnable}' where ProgramKey='{model.ProgramKey}' ");
                                                if (i >= 0)
                                                {
                                                    httpResponseResultModel.IsSuccess = true;
                                                }
                                                else
                                                {
                                                    httpResponseResultModel.IsSuccess = false;
                                                }

                                            }
                                            catch (Exception ex)
                                            {

                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/DeleteMulttipRemoteCardInfo":
                                        {
                                            try
                                            {
                                                MultipleNetworkCardManageEntity model = JsonConvert.DeserializeObject<MultipleNetworkCardManageEntity>(questBody);
                                                var i = SQLiteHelper.ExecuteSql($"delete from  MultipleNetworkCardManage where ProgramKey='{model.ProgramKey}' ");
                                                if (i >= 0)
                                                {
                                                    httpResponseResultModel.IsSuccess = true;
                                                }
                                                else
                                                {
                                                    httpResponseResultModel.IsSuccess = false;
                                                }

                                            }
                                            catch (Exception ex)
                                            {

                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/InitSysInfo":
                                        {
                                            WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("InitSys"), "InitSys");
                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postAddAlarmPushData":
                                        {
                                            try
                                            {
                                                AlarmPushManageEntity model = JsonConvert.DeserializeObject<AlarmPushManageEntity>(questBody);

                                                SQLiteHelper.ExecuteSql($"insert into AlarmPushManage (ProgramKey,Api,Method,ParamStr,IsEnable,CreateTime)" +
                                        $" values('{model.ProgramKey}','{model.Api}','{model.Method}','{model.ParamStr}','{model.IsEnable}','{DateTime.Now.ToString()}')");

                                                httpResponseResultModel.IsSuccess = true;
                                            }
                                            catch (Exception ex)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                            }

                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postUpdateAlarmPushData":
                                        {
                                            AlarmPushManageEntity model = JsonConvert.DeserializeObject<AlarmPushManageEntity>(questBody);

                                            SQLiteHelper.ExecuteSql($"update AlarmPushManage set Api='{model.Api}',Method='{model.Method}',ParamStr='{model.ParamStr}',IsEnable='{model.IsEnable}'  where ProgramKey='{model.ProgramKey}'");

                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postDelAlarmPushData":
                                        {
                                            AlarmPushManageEntity model = JsonConvert.DeserializeObject<AlarmPushManageEntity>(questBody);

                                            SQLiteHelper.ExecuteSql($"delete from  AlarmPushManage where ProgramKey='{model.ProgramKey}' ");

                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postAutoUpdateSwatch":
                                        {
                                            try
                                            {
                                                AutoSwitchEntity model = JsonConvert.DeserializeObject<AutoSwitchEntity>(questBody);
                                                IniFileConfig.Current.SetStringValue("UserConfig", "IsAutoSwitch", model.IsAutoSwitch);
                                                httpResponseResultModel.IsSuccess = true;
                                            }
                                            catch (Exception ex)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                                LoggerHelper.Error(ex.Message, "API");
                                            }

                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postAutoStartUpdateSwatch":
                                        {
                                            try
                                            {
                                                AutoSwitchEntity model = JsonConvert.DeserializeObject<AutoSwitchEntity>(questBody);
                                                var enable = false;
                                                bool.TryParse(model.IsAutoSwitch, out enable);
                                                RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                                                if (enable)
                                                {
                                                    var FileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                                                    LoggerHelper.Info(FileName, "SetAutoStart");
                                                    key.SetValue("HsServerHa", FileName + " /autorun");
                                                }
                                                else
                                                {
                                                    key.DeleteValue("HsServerHa", false);
                                                }
                                                httpResponseResultModel.IsSuccess = true;
                                            }
                                            catch (Exception ex)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                                LoggerHelper.Error(ex.Message, "API");
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postStartDaemonUpdateSwatch":
                                        {
                                            try
                                            {
                                                AutoSwitchEntity model = JsonConvert.DeserializeObject<AutoSwitchEntity>(questBody);
                                                var enable = false;
                                                bool.TryParse(model.IsAutoSwitch, out enable);
                                                IniFileConfig.Current.SetStringValue("UserConfig", "IsStartDaemon", enable + "");
                                                httpResponseResultModel.IsSuccess = true;
                                            }
                                            catch (Exception ex)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                                LoggerHelper.Error(ex.Message, "API");
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postStartSyncFileUpdateSwatch":
                                        {
                                            try
                                            {
                                                AutoSwitchEntity model = JsonConvert.DeserializeObject<AutoSwitchEntity>(questBody);
                                                var enable = false;
                                                bool.TryParse(model.IsAutoSwitch, out enable);
                                                IniFileConfig.Current.SetStringValue("UserConfig", "IsStartSyncFile", enable + "");
                                                httpResponseResultModel.IsSuccess = true;
                                            }
                                            catch (Exception ex)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                                LoggerHelper.Error(ex.Message, "API");
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postSetMACAddress":
                                        {
                                            try
                                            //todo:设置MACAddress
                                            {
                                                SetMACAddressEntity model = JsonConvert.DeserializeObject<SetMACAddressEntity>(questBody);
                                                var networkInterface = NetWorkHelper.GetAdapterByName(model.CardName);
                                                int result = NetWorkHelper.SetMacAddress(networkInterface.Description, model.MAC);
                                                httpResponseResultModel.IsSuccess = result == 0 ? true : false;
                                            }
                                            catch (Exception ex)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = ex.Message;
                                                LoggerHelper.Error(ex.Message, "API");
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/deleteDbBack":
                                        {
                                            string directoryPath = @"D:\dbback"; // 指定要删除的目录路径
                                            // 删除目录以及目录下的所有文件和子目录
                                            try
                                            {
                                                DbBackFilePathEntity model = JsonConvert.DeserializeObject<DbBackFilePathEntity>(questBody);
                                                if (model != null && !string.IsNullOrEmpty(model.FilePath))
                                                {
                                                    directoryPath = model.FilePath;
                                                }

                                                string[] files = Directory.GetFiles(directoryPath);
                                                foreach (string file in files)
                                                {
                                                    File.Delete(file);
                                                }
                                                httpResponseResultModel.IsSuccess = true;
                                            }
                                            catch (IOException e)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = e.Message;
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                   
                                    case "/syncDbBackPath":
                                        {
                                            string directoryPath = @"D:\dbback"; // 指定要删除的目录路径
                                            //删除目录以及目录下的所有文件和子目录
                                            try
                                            {
                                                DbBackFilePathEntity model = JsonConvert.DeserializeObject<DbBackFilePathEntity>(questBody);
                                                if (model != null && !string.IsNullOrEmpty(model.FilePath))
                                                {
                                                    directoryPath = model.FilePath;
                                                }
                                                SQLiteHelper.ExecuteSql($"delete from  DbBackFilePath");
                                                var parms = new DbBackFilePathEntity
                                                {
                                                    FilePath = model.FilePath,
                                                    UpdateTime = DateTime.Now.ToString()
                                                };
                                                SQLiteHelper.ExecuteSql($"insert into DbBackFilePath (FilePath,UpdateTime)" +
                                                                         $" values('{parms.FilePath}','{parms.UpdateTime}')");

                                                if (!FileHelpers.CreateDic(directoryPath))
                                                {
                                                    httpResponseResultModel.IsSuccess = false;
                                                    httpResponseResultModel.ErrorMessage = "远程文件夹创建失败";
                                                }
                                                else
                                                {
                                                    httpResponseResultModel.IsSuccess = true;
                                                }

                                            }
                                            catch (IOException e)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = e.Message;
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/setTcpListener":
                                        {

                                            try
                                            {
                                                TransFileEntity model = JsonConvert.DeserializeObject<TransFileEntity>(questBody);
                                                int port = model.Port; // 设置监听的端口号
                                                TcpListener FileListener = new TcpListener(IPAddress.Any, port);
                                                FileListener.Start();
                                                LoggerHelper.Info("监听已启动,等待连接...", "数据库备份文件复制监听");

                                                string targetFilePath = model.FilePath;
                                                bool isCanExecute = true;
                                                while (isCanExecute)
                                                {
                                                    TcpClient fileClient = FileListener.AcceptTcpClient();
                                                    NetworkStream fileNetworkStream = fileClient.GetStream();

                                                    byte[] buffer = new byte[8096];
                                                    int bytesRead;

                                                    using (FileStream fileStream = File.OpenWrite(targetFilePath)) // 设置目标文件路径
                                                    {
                                                        while ((bytesRead = fileNetworkStream.Read(buffer, 0, buffer.Length)) > 0)
                                                        {
                                                            fileStream.Write(buffer, 0, bytesRead);
                                                        }
                                                    }
                                                    fileNetworkStream.Close();
                                                    fileClient.Close();
                                                    LoggerHelper.Info("文件保存完成", "数据库备份文件复制监听");
                                                    isCanExecute = false;
                                                }
                                                httpResponseResultModel.IsSuccess = true;


                                            }
                                            catch (IOException e)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = e.Message;
                                                LoggerHelper.Info($"{e.Message}", "数据库备份文件复制监听");
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/sendCertificateFile":
                                        {

                                            try
                                            {
                                                bool isCanExecute = true;
                                                TransFileEntity model = JsonConvert.DeserializeObject<TransFileEntity>(questBody);
                                                //执行失败一直执行
                                                while (isCanExecute)
                                                {
                                                    var result = FileTransferClient.TransferFile(model.ServerIp, model.Port, model.FilePath);
                                                    if (result)
                                                    {
                                                        isCanExecute = false;
                                                        LoggerHelper.Info($"{model.FilePath}同步完成");
                                                    }
                                                    else
                                                    {
                                                        //未能连接远程服务器重新调用接口启动远程监听
                                                        LoggerHelper.Error($"{model.FilePath}未能连接远程服务器重新调用接口启动远程监听,端口：{model.Port}");

                                                    }

                                                }
                                                httpResponseResultModel.IsSuccess = true;


                                            }
                                            catch (IOException e)
                                            {
                                                httpResponseResultModel.IsSuccess = false;
                                                httpResponseResultModel.ErrorMessage = e.Message;
                                                LoggerHelper.Info($"{e.Message}", "数据库备份文件复制监听");
                                            }
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postSqlManageAdd":
                                        {
                                            SQLManageEntity model = JsonConvert.DeserializeObject<SQLManageEntity>(questBody);

                                            var parms = new SQLManageEntity
                                            {
                                                ProgramKey = GeneratePrimaryKeyIdHelper.GetPrimaryKeyId().ToString(),
                                                DBName = model.DBName,
                                                Port = model.Port,
                                                UserId = model.UserId,
                                                UserPwd = model.UserPwd,
                                                IsEnable = model.IsEnable,
                                                CreateTime = DateTime.Now.ToString()
                                            };
                                            SQLiteHelper.ExecuteSql($"insert into SQLManage (ProgramKey,DBName,Port,UserId,UserPwd,IsEnable,CreateTime)" +
                                                                    $" values('{parms.ProgramKey}','{parms.DBName}','{parms.Port}','{parms.UserId}','{parms.UserPwd}','{parms.IsEnable}','{DateTime.Now.ToString()}')");

                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postSqlManageDeleteData":
                                        {
                                            //删除配置表数据
                                            SQLiteHelper.ExecuteSql($"delete from  SQLManage");
                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    case "/postSqlManageDeleteByDBName":
                                        {
                                            SQLManageEntity model = JsonConvert.DeserializeObject<SQLManageEntity>(questBody);
                                            SQLiteHelper.ExecuteSql($"delete from SQLManage where DBName='{model.DBName}' ");
                                            //删除备份文件
                                            DbBackFilePathEntity dbBackFilePathEntity = SQLiteHelper.Table<DbBackFilePathEntity>().FirstOrDefault();
                                            var dbBackFiles = new List<string>();
                                            if (dbBackFilePathEntity != null)
                                            {
                                                dbBackFiles.Add($"{dbBackFilePathEntity.FilePath}\\{model.DBName}.bak");
                                                dbBackFiles.Add($"{dbBackFilePathEntity.FilePath}\\{model.DBName}_log.bak");
                                            }
                                            foreach (string file in dbBackFiles)
                                            {
                                                File.Delete(file);
                                            }




                                            httpResponseResultModel.IsSuccess = true;
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                    default:
                                        {
                                            LoggerHelper.Error(rawUrl + "接口不存在");
                                            httpResponseResultModel.IsSuccess = false;
                                            httpResponseResultModel.BackResult = "接口不存在";
                                            responseWrite(httpResponseResultModel, response);
                                            break;
                                        }
                                }



                            }
                            else
                            {
                                LoggerHelper.Error(rawUrl + "接口不存在");
                                httpResponseResultModel.IsSuccess = false;
                                httpResponseResultModel.BackResult = "Success";
                                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(httpResponseResultModel));
                                //对客户端输出相应信息.
                                response.ContentLength64 = buffer.Length;
                                response.StatusCode = 200;
                                response.ContentType = "text/plain";
                                //发送响应
                                using (System.IO.Stream output = response.OutputStream)
                                {
                                    output.Write(buffer, 0, buffer.Length);
                                }
                            }


                        }
                        catch (Exception ex)
                        {
                            LoggerHelper.Error("接口异常:" + ex.Message);
                            //Logger.Error("处理消息异常", exceotion);
                            string str = ex.Message;
                            var result = new HttpResponseResultModel<object> { ErrorMessage = ex.Message, IsSuccess = false };
                            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
                            //对客户端输出相应信息.
                            response.ContentLength64 = buffer.Length;
                            response.StatusCode = 200;
                            response.ContentType = "text/plain";
                            //发送响应
                            using (System.IO.Stream output = response.OutputStream)
                            {
                                output.Write(buffer, 0, buffer.Length);
                            }
                        }
                    }
                }
                else
                {
                    LoggerHelper.Error("Http服务启动失败");
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(ex.Message + ex.ToString());
            }

        }

        private static void responseWrite(HttpResponseResultModel<object> httpResponseResultModel, HttpListenerResponse response)
        {
            var responseString = JsonConvert.SerializeObject(httpResponseResultModel);
            httpResponseResultModel.HttpStatusCode = HttpStatusCode.OK;
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            //对客户端输出相应信息.
            response.ContentLength64 = buffer.Length;
            response.StatusCode = 200;
            response.ContentType = "text/plain";
            //发送响应
            using (System.IO.Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
            }
        }

        /// <summary>
        /// 重启
        /// </summary>
        /// <param name="networkCardName">网卡名称</param>
        public static void ReStart(string networkCardName)
        {
            Stop();
            isExcute = true;
            Start(networkCardName);
        }
        public static void Stop()
        {
            isExcute = false;
            if (listener != null)
            {
                if (listener.IsListening)
                {
                    listener.Stop();
                    listener = null;
                }
            }

        }
    }
    public class UploadGenConnectedModel
    {
        public bool GenConnected { get; set; }
    }
}
